package top.csy8888.ch06.service;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.util.UUID;

/**
 * @author CSY
 * @date 2025 - 10 - 14
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class ProducerService {
    private final RabbitTemplate rabbitTemplate;

    /**
     * 消息确认投递到交换机中
     * @param message
     */
    public void send(String message){
        // 创建消息的唯一ID
        CorrelationData correlationData = new CorrelationData();
        correlationData.setId(UUID.randomUUID().toString());

        rabbitTemplate.convertAndSend("test.exchange","key.test",message,correlationData);

        // 通过一个回调来接收rabbitmq返回的ack
        //由于设置了ConfirmCallback，因此消息只要到达exchange，返回的ack就为true
        rabbitTemplate.setConfirmCallback((cdata,ack,cause) -> {
            String id = cdata.getId();
            if(!ack){
                log.info("消息{}投递失败",id);
            }else {
                log.info("消息{}投递成功",id);
            }
        });
    }

    /**
     * 消息确认投递到队列中
     * @param message
     */
    public void sendTwo(String message){
        // 创建消息的唯一ID
        CorrelationData correlationData = new CorrelationData();
        correlationData.setId(UUID.randomUUID().toString());

        rabbitTemplate.convertAndSend("test.exchange","key.test",message,correlationData);

        //确认消息是否投递到队列中
        //注意：只有消息未正确到达队列时才会执行这个回调
        rabbitTemplate.setReturnsCallback(returnedMessage -> {
            log.info("内容：{}",new String(returnedMessage.getMessage().getBody(), StandardCharsets.UTF_8));
            log.info("确认码：{}",returnedMessage.getReplyCode());
            log.info("路由的key：{}",returnedMessage.getRoutingKey());
        });
    }

}
